<?php
/**
 * Created by PhpStorm.
 * User: niqiaoyun
 * Date: 2017/9/5
 * Time: 09:31
 */

namespace app\models;

use Yii;
use app\models\dao\RoleNav;
use app\common\widgets\Tools;
use app\models\dao\Role;
use app\models\dao\RoleAccess;
use app\models\dao\RoleNode;
use yii\db\Exception;

class RoleModel extends Role {

	public function getAll($query = [],$page = []) {
		$where = [];
		if(!empty($query['where'])) {
			$where = $query['where'];
		}

		$query_order = ['id'=>SORT_DESC];
		$query_wheres = ['and'];
		$query_wheres[] = " flag = 1 ";
		if (!empty($where['name'])) {
			$query_wheres[] = ['name'=>$where['name']];
		}
		// 读取总条数
		$count = $this->count($query_wheres);

		$offset = ($page['pageno'] - 1) * $page['pagesize'];
		$limit = $page['pagesize'];

		// 计算分页
		$arr_rows = Role::find()->where($query_wheres)->orderBy($query_order)->limit($limit)->offset($offset)->asArray()->all();
		return Tools::formatPage($arr_rows, $count);
	}

	public function getOne($int_id) {
		$arr_rows = Role::find()->where(['id' => $int_id, 'flag' => 1])->one();
		if(empty($arr_rows)) {
			return array();
		}
		return $arr_rows;
	}

	public function create($array_params) {
		$str_datetime = date("Y-m-d H:i:s");
		$createObj = new Role();
		$bool_save = $createObj->setData($array_params)->insert();
		if(true === $bool_save) {
			return array('status'=>true,'msg'=>'success','data'=>array('name'=>$array_params['name'],'create_time'=>$str_datetime));
		}else {
			return array('status'=>false,'msg'=>'error');
		}
	}

	/**
	 * 更新行业分类信息
	 * @param array $data
	 */
	public function modify($data = []) {
		// 保存数据
		$int_id = (int)$data['id'];
		unset($data['id']);
		$modifyObj = new Role();
		$update_result = $modifyObj->updateAll($data, 'id = :id',
			[':id'=>$int_id]);
		if ($update_result >= 0) {
			return true;
		} else {
			return false;
		}
	}

	public function count($where = []) {
		$count = Role::find()->where($where)->asArray()->count(1);
		return $count;
	}

	public function CheckName($where) {
		$query_wheres = ['and'];
		$query_wheres[] = ['name'=>$where['name'], 'flag' => 1];
		if (!empty($where['id'])) {
			$query_wheres[] = ['<>','id', $where['id']];
		}

		$ary_result = Role::find()->where($query_wheres)->one();
		if(empty($ary_result)) {
			return false;
		}
		return true;
	}

	public function modifyPk($pk, $attributes) {
		if(empty($pk)) {
			return false;
		}
		$params = [];
		$modifyObj = new Role();
		foreach($pk as $key=>$val) {
			$params[':id'] = $val;
			$update_result = $modifyObj->updateAll($attributes, "id=:id", $params);
		}

		if ($update_result >= 0) {
			return true;
		} else {
			return false;
		}
	}

	public function getMenus($userType = 0) {
		$query_order = ['sort'=>SORT_DESC];
		$query_wheres = ['and'];
		$query_wheres[] = " flag = 1 and status = 1 AND type=".$userType;
		$arr_rows = RoleNav::find()->where($query_wheres)->orderBy($query_order)->asArray()->all();
		if(!empty($arr_rows)) {
			foreach($arr_rows as $key=>&$rows) {
				$roleNode = RoleNode::find()->where(['nav_id' => $rows['id'], 'parent_id' => 0, 'status' => 1, 'flag' => 1, 'type' => $userType])->orderBy('sort desc')->asArray()->all();
				if(!empty($roleNode)) {
					$rows['childMenu'] = $roleNode;
					foreach($roleNode as $ky=>&$node) {
						$nodeAccess = RoleNode::find()->where(['nav_id' => $rows['id'], 'parent_id' => $node['id'], 'status' => 1, 'flag' => 1, 'type' => $userType])->orderBy('sort desc')->asArray()->all();
						if(!empty($nodeAccess)) {
							$rows['childMenu'][$ky]['childMenu'] = $nodeAccess;
						}

					}
				}
			}
		}
		return $arr_rows;
	}

	/**
	 * @param bool $paramsData
	 * @param array|null $accessNode
	 * @return array
	 * @throws Exception
	 * @throws \Throwable
	 * @throws \yii\db\Exception
	 */
	public function saved($paramsData, $accessNode) {
		if(empty($paramsData) || empty($accessNode)) {
			return array('status'=>false,'msg'=>'error');
		}
		// 开启事务
		$transaction = \Yii::$app->db->beginTransaction ();
		try {
			$createObj = new RoleModel();
			$bool_save = $createObj->setData($paramsData)->insert();
			if(false == $bool_save) {
				throw new Exception("保存角色信息失败，请重试", 104050);
			}
			$role_id = (int)$createObj->attributes['id'];
			if($role_id <= 0) {
				throw new Exception("保存角色信息失败，请重试", 104051);
			}

			$keyname = [];
			$valuename = [];
			$parent_params = [];
			foreach($accessNode as $key=>$node) {
				$nodeArr = explode(":", $node);
				$int_node_id = $nodeArr[2];
				$parent_params[$key]['node_id'] = $int_node_id;
				$parent_params[$key]['role_id'] = $role_id;
				foreach($parent_params[$key] as $ky=>$vl) {
					if(!in_array($ky, $keyname)) {
						$keyname[] = $ky;
					}
					$valuename[$key][] = $vl;
				}
			}

			$ary_batch_result = \Yii::$app->db->createCommand()->batchInsert(RoleAccess::tableName(), $keyname, $valuename)->execute();
			if(FALSE == $ary_batch_result || $ary_batch_result <= 0) {
				throw new Exception("批量插入信息失败，请重试", 104052);
			}
			$transaction->commit();
		} catch( \Exception $e ) {
			$transaction->rollback();
			return array('status'=>false,'msg'=> $e->getMessage ());
		}
		return array('status'=>true,'msg'=>'success','data'=>array());
	}

	public function updated($paramsData, $accessNode) {
		if(empty($paramsData) || empty($accessNode)) {
			return array('status'=>false,'msg'=>'error');
		}
		$transaction = \Yii::$app->db->beginTransaction ();
		$int_role_id = $paramsData['role_id'];
		try {
			$attributes = array(
				'name'	=> $paramsData['name'],
				'description'	=> $paramsData['description'],
				'status'    => $paramsData['status']
			);
			$condition = 'id=:role_id';
			$params = array(
				':role_id' => $int_role_id,
			);
			$companyObj = new Role();
			$result = $companyObj->updateAll($attributes, $condition, $params);

			if (false === $result) {
				throw new Exception("更新角色信息失败，请重试", 104048);
			}
			$del_condition = "role_id =:role_id";
			$del_params = array(
				':role_id' => $int_role_id,
			);
			$del_result = RoleAccess::deleteAll($del_condition,$del_params);

			if (false === $del_result) {
				throw new Exception("删除角色信息失败，请重试", 104049);
			}
			$keyname = [];
			$valuename = [];
			$parent_params = [];

			foreach($accessNode as $key=>$node) {
				$nodeArr = explode(":", $node);
				$int_node_id = $nodeArr[2];
				$parent_params[$key]['node_id'] = $int_node_id;
				$parent_params[$key]['role_id'] = $int_role_id;
				foreach($parent_params[$key] as $ky=>$vl) {
					if(!in_array($ky, $keyname)) {
						$keyname[] = $ky;
					}
					$valuename[$key][] = $vl;
				}
			}

			$ary_batch_result = \Yii::$app->db->createCommand()->batchInsert(RoleAccess::tableName(), $keyname, $valuename)->execute();
			if(FALSE == $ary_batch_result || $ary_batch_result <= 0) {
				throw new Exception("批量插入信息失败，请重试", 104052);
			}
			$transaction->commit();
		} catch( \Exception $e ) {
			$transaction->rollback();
			return array('status'=>false,'msg'=> $e->getMessage ());
		}
		return array('status'=>true,'msg'=>'success','data'=>array());
	}
}